package com.songcha.module_mine.ui.activity.userinfo


import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.helper.PermissionTipHelper
import com.songcha.library_common.ui.dialog.CustomDialog
import com.songcha.library_common.ui.dialog.InputDialog
import com.songcha.library_common.ui.dialog.ListDialog
import com.songcha.library_common.util.GlideUtil
import com.songcha.library_common.util.ScreenUtil
import com.songcha.library_common.util.StringUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.module_mine.R
import com.songcha.module_mine.databinding.MineActivityUserinfoBinding
import com.songcha.module_mine.ui.activity.bind_phone.BindPhoneActivity
import com.songcha.module_mine.util.GlideEngine
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File


class UserInfoActivity : BaseMvvmActivity<UserInfoViewModel,MineActivityUserinfoBinding>(){
    companion object{
        private val AVATAR_OUT_SIZE=100//avatar clip size
    }

    private var mPermissions:RxPermissions?=null

    override fun getLayoutId(): Int {
        return R.layout.mine_activity_userinfo
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        showUserInfo()

        mPermissions=RxPermissions(this)

        //使用glide显示选择的图片
        /*ISNav.getInstance().init { context, path, imageView ->
            Glide.with(context).load(path).into(imageView)
        }*/

        databinding.mineCclModifyAvatar.setOnClickListener {
            showSelectImageDialog()
        }

        databinding.mineLlModifyNickname.setOnClickListener {
            showModifyNickNameDialog()
        }

        databinding.mineLlModifyPhone.setOnClickListener {
            val intent=Intent(it.context,BindPhoneActivity::class.java)
            intent.putExtra("is_change",UserInfoManager.userInfo!!.phonenumber.isNotEmpty())
            startActivity(intent)
        }

        databinding.mineBtnLogout.setOnClickListener {
            showLogoutDialog()
        }


        viewModel.apiState.observe(this){data->
            if(data){
                ToastUtil.show("修改成功")
            }
            showUserInfo()
        }

    }

    private fun showUserInfo(){
        if(UserInfoManager.checkLogin()){
            databinding.mineBtnLogout.visibility= View.VISIBLE
            databinding.mineTvNickName.text=UserInfoManager.userInfo!!.userNick
            val phone = if(UserInfoManager.userInfo!!.phonenumber.isNotEmpty()) UserInfoManager.userInfo!!.phonenumber else "未绑定"
            databinding.mineTvPhone.text=StringUtil.hidePhoneMiddleNumber(phone)
            GlideUtil.loadNetImage(databinding.mineIvAvatar,UserInfoManager.userInfo!!.avatar)
            if(FunctionConfig.IS_VIP_ENABLED){
                if(UserInfoManager.isVip()){
                    databinding.mineIvVip.visibility=View.VISIBLE
                }else{
                    databinding.mineIvVip.visibility=View.GONE
                }
            }
        }else{
            databinding.mineBtnLogout.visibility= View.GONE
            databinding.mineIvAvatar.setImageResource(com.songcha.library_business.R.mipmap.business_icon_avatar_nologin)
        }

    }

    override fun onResume() {
        super.onResume()
        showUserInfo()
    }

    private fun showLogoutDialog(){
        val db=CustomDialog.Companion.Builder(this)
        db.setDialogMsg("是否退出登录？")
            .setOnConfirmListener {
                viewModel.logout()
                ToastUtil.show("已退出登录")
                finish()
                true
            }
            .create()
            .show()
    }

    private fun showModifyNickNameDialog(){
        val dialog=InputDialog(this)
        dialog.setDialogTitle("修改昵称")
        dialog.setDialogMsg("")
        dialog.setOnConfirmListener {
            val nickName=dialog.getInput()
            if(nickName.isBlank()){
                ToastUtil.show("请输入昵称")
                return@setOnConfirmListener true
            }
            if(nickName.length>10){
                ToastUtil.show("昵称不能超过10个字符")
                return@setOnConfirmListener true
            }
            viewModel.modifyNickName(dialog.getInput(),UserInfoManager.userInfo!!.id)
            true
        }
        dialog.show()
    }


    private fun showSelectImageDialog(){
        if(mPermissions==null) return
        val list= mutableListOf("拍照","选择照片")
        val dialog=ListDialog(this,list)
        dialog.apply {
            setRadius(floatArrayOf(15f.dp2px(),15f.dp2px(),0f,0f))
            setDialogTitle("修改头像")
            setDialogMsg("")
            setWidth(ScreenUtil.getScreenWidth())
            setGravity(Gravity.BOTTOM)
            setAnim(com.songcha.library_common.R.style.dialogBottomSlideWindowAnim)
            setOnListDialogItemClickListener{p->
                if(p==0){
                    val tipString = "我们需要获取您的拍照和存储访问权限，用于拍摄上传头像图片"
                    val isGranted=mPermissions?.isGranted(Manifest.permission.CAMERA)?:false
                    if(!isGranted){
                        val dialogTip = PermissionTipHelper.showPermissionTip(context,tipString)
                        mPermissions?.request(Manifest.permission.CAMERA)
                            ?.subscribe {
                                dialogTip.dismiss()
                                if (it) {
                                    takePhoto()
                                } else {

                                }
                            }
                    }else{
                        takePhoto()
                    }

                }else{
                    val tipString = "我们需要获取您的存储访问权限，用于上传本地头像图片"
                    var permission:String = Manifest.permission.WRITE_EXTERNAL_STORAGE
                    if(Build.VERSION.SDK_INT>=33)
                        permission = Manifest.permission.READ_MEDIA_IMAGES

                    val isGranted=mPermissions?.isGranted(permission)?:false
                    if(!isGranted){
                        val dialogTip = PermissionTipHelper.showPermissionTip(context,tipString)
                        mPermissions?.request(permission)
                            ?.subscribe {
                                dialogTip.dismiss()
                                if (it) {
                                    selectImage()
                                } else {

                                }
                            }
                    }else{
                        selectImage()
                    }

                }
                return@setOnListDialogItemClickListener true
            }

        }
        dialog.show()
    }


    private fun takePhoto(){
        PictureSelector.create(this)
            .openCamera(SelectMimeType.ofImage())
            .setCropEngine(MyCropFileEngine(this))
            .setCompressEngine(MyCompressFileEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    if(result.size==0) return
                    val media=result[0]
                    if(!media.compressPath.isNullOrBlank()){
                        val file=File(media.compressPath)
                        viewModel.uploadAvatar(file)
                    }
                }
                override fun onCancel() {}
            })
    }

    private fun selectImage(){
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setMaxSelectNum(1)
            .setCropEngine(MyCropFileEngine(this))
            .setCompressEngine(MyCompressFileEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia>{
                override fun onResult(result: ArrayList<LocalMedia>) {
                    if(result.size==0) return
                    val media=result[0]
                    if(!media.compressPath.isNullOrBlank()){
                        val file=File(media.compressPath)
                        viewModel.uploadAvatar(file)
                    }
                }

                override fun onCancel() {

                }

            })

    }

    class MyCropFileEngine(val mContext:Context):CropFileEngine{
        override fun onStartCrop(
            fragment: Fragment,
            srcUri: Uri,
            destinationUri: Uri,
            dataSource: ArrayList<String>,
            requestCode: Int
        ) {
            val uCrop = UCrop.of(srcUri, destinationUri, dataSource)
            uCrop.setImageEngine(object :UCropImageEngine{
                override fun loadImage(
                    context: Context,
                    url: String,
                    imageView: ImageView
                ) {
                    try{
                        Glide.with(context).load(url).into(imageView)
                    }  catch (e:Exception){
                        e.printStackTrace()
                    }
                }

                override fun loadImage(
                    context: Context,
                    url: Uri,
                    maxWidth: Int,
                    maxHeight: Int,
                    call: UCropImageEngine.OnCallbackListener<Bitmap>
                ) {
                    try{
                        Glide.with(context).asBitmap().override(maxWidth, maxHeight).load(url).into(object: CustomTarget<Bitmap>() {
                            override fun onResourceReady(
                                resource: Bitmap,
                                transition: Transition<in Bitmap>?
                            ) {
                                if (call != null) {
                                    call.onCall(resource)
                                }
                            }

                            override fun onLoadCleared(placeholder: Drawable?) {
                                if (call != null) {
                                    call.onCall(null)
                                }
                            }

                        })
                    }  catch (e:Exception){
                        e.printStackTrace()
                    }
                }


            })

            val options=UCrop.Options().apply {
                withMaxResultSize(AVATAR_OUT_SIZE,AVATAR_OUT_SIZE)
            }
            uCrop.withOptions(options)
            uCrop.start(mContext, fragment, requestCode)
        }
    }

    class MyCompressFileEngine:CompressFileEngine{
        override fun onStartCompress(
            context: Context,
            source: ArrayList<Uri>,
            call: OnKeyValueResultCallbackListener
        ) {
            Luban.with(context).load(source).ignoreBy(100)
                .setCompressListener(object : OnNewCompressListener{
                    override fun onStart() {

                    }

                    override fun onSuccess(source: String, compressFile: File) {
                        if (call != null) {
                            call.onCallback(source, compressFile.getAbsolutePath())
                        }
                    }

                    override fun onError(source: String, e: Throwable?) {
                        if (call != null) {
                            call.onCallback(source, null)
                        }
                    }

                }).launch()
        }
    }

}



